import axios from 'axios';
import { showDialog, showToast } from 'vant';
import { envConfig } from './env';
import { store } from '@/store/store';

const request = axios.create({
  baseURL: envConfig.apiBaseUrl,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

let loadingCount = 0;

function showLoading() {
  loadingCount++;
  if (loadingCount === 1) {
    store().setLoading(true);
  }
}

function hideLoading() {
  loadingCount--;
  if (loadingCount === 0) {
    store().setLoading(false);
  }
}

// 请求拦截器
request.interceptors.request.use(
  config => {
    showLoading();
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    hideLoading();
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  response => {
    hideLoading();
    return response.data;
  },
  error => {
    hideLoading();
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      window.location.href = '/#/login';
      showToast({ type: 'fail', message: '请先登录' });
    } else {
      showToast({ type: 'fail', message: error.response?.data?.message || '请求失败' });
    }
    return Promise.reject(error);
  }
);

export default request;